package com.web.service;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.web.config.JWTConfig;
import com.web.dao.UserMapper;
import com.web.model.ResponseData;
import com.web.model.UserModel;
import com.web.params.LoginParams;
import com.web.params.PersonEditParams;
import com.web.params.RegistryParams;

import cn.hutool.core.bean.BeanUtil;



@Service
public class UserService {
	@Autowired
	private UserMapper userMapper;
	public ResponseData registry( RegistryParams params) {
		String username = params.getUsername();
		String nickName = params.getNickName();	
		String hasUsername = userMapper.hasUsername(username);
		String hasnickName = userMapper.hasnickName(nickName,username);
		ResponseData responseData = new ResponseData();
		if(hasUsername !=null) {
			responseData.failed("注册失败，用户名被占用");
		}else if(hasnickName != null) {
			responseData.failed("注册失败，昵称被占用");
		}else {
			int result = userMapper.registry(params);
			if (result > 0) {
				responseData.success("注册成功，请登录");
			} else {
				responseData.failed("注册失败，请联系管理员");
			}
}
		return responseData;
	}
	public ResponseData login(LoginParams params) {
		 String loginUsername = params.getUsername();
	     String loginPassword= params.getPassword();
	     String dbPassword = userMapper.login(loginUsername);
		 	 ResponseData responseData = new ResponseData();
		     if(dbPassword == null) {//表示用户不存在
		    	 responseData.failed("登录失败，用户名没有注册");
		     }else if(loginPassword.equals(dbPassword)) {//表示登录成功
		    	 //查询作者信息
		    	 UserModel userModel = userMapper.getuser(loginUsername);
		    	 Map<String, Object> payloadMap = BeanUtil.beanToMap(userModel);
		    	 //生成JWT令牌
		    	 String token = JWTConfig.gen(payloadMap);
		    	 responseData.success("登录成功", token);
		    }else {//表示密码输入错误
		    	responseData.failed("登录失败,用户名或密码错误");
		    }
		        return responseData;

}
	//个人信息修改
	public  ResponseData Personedit(PersonEditParams params) {
		String hasnickname = userMapper.hasnickName(params.getNickname(), params.getUsername());
		ResponseData responseData =new ResponseData();
		if(hasnickname == null ){
			int result = userMapper.updateperson(params);
			if(result>0) {
				UserModel userModel = userMapper.getuser(params.getUsername());
				responseData.success("修改成功", userModel);
			}else {
				responseData.failed("修改失败，请联系管理员");
			}
		}else {
			responseData.failed("笔名重复");
		}
		return responseData;
	}
		
		
	}
